<template>
  <div class="standardForm">
    <div class="form-header">
      <h1>form1</h1>
      <a-button type="primary" @click="showDrawer"> 显示表单结果 </a-button>
    </div>
    <section>
      <a-form ref="formRef1" layout="vertical" :model="formState1" :rules="rules1">
        <a-form-item label="页面名称" name="app">
          <a-input v-model:value="formState1.app" placeholder="请输入页面名称" allow-clear />
        </a-form-item>
        <a-form-item label="页面链接" name="url">
          <a-input v-model:value="formState1.url" placeholder="请输入页面名称" allow-clear />
        </a-form-item>
        <a-form-item label="背景图片" name="icon">
          <a-upload
            v-model:file-list="formState1.icon"
            action="/"
            :beforeUpload="handleBeforeUpload"
            :max-count="1"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              上传图片
            </a-button>
            <span class="tips">（大小不超过50M,支持jpg/png格式）</span>
          </a-upload>
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="submit1">提交</a-button>
    </section>
    <h1>form2</h1>
    <section>
      <a-form
        ref="formRef2"
        :model="formState2"
        :rules="rules2"
        :label-col="labelCol2"
        :wrapper-col="wrapperCol2"
      >
        <a-form-item ref="name" label="组织名称" name="name">
          <a-input v-model:value="formState2.name" placeholder="请输入组织名称" allow-clear />
        </a-form-item>
        <a-form-item label="从属上级组织" name="subordinate">
          <a-select
            v-model:value="formState2.subordinate"
            show-search
            :filter-option="filterOption"
            placeholder="请选择上级组织"
            allow-clear
            :options="options"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="组织负责人" name="principal">
          <a-select
            v-model:value="formState2.principal"
            show-search
            :filter-option="filterOption"
            placeholder="请选择组织负责人"
            allow-clear
            :options="options2"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="常态阈值范围">
          <div style="display: flex">
            <a-form-item name="value2">
              <a-input v-model:value="formState2.value2" />
            </a-form-item>
            <span style="display: inline-block; width: 24px; line-height: 32px; text-align: center">
              ~
            </span>
            <a-form-item name="value3">
              <a-input v-model:value="formState2.value3" />
            </a-form-item>
          </div>
        </a-form-item>
        <a-form-item label="节点处理人" name="value4">
          <a-select
            v-model:value="formState2.value4"
            show-search
            mode="multiple"
            :filter-option="filterOption"
            placeholder="请选择处理人"
            allow-clear
            :options="options4"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="节点处理方式" name="value5">
          <a-select
            v-model:value="formState2.value5"
            show-search
            placeholder="请选择处理方式"
            allow-clear
            :options="options5"
          >
          </a-select>
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="submit2">提交</a-button>
    </section>

    <!-- 侧边栏组件 -->
    <a-drawer 
      title="表单数据结果" 
      :open="drawerVisible" 
      @close="drawerVisible = false" 
      width="500"
      rootClassName="form-result-drawer"
    >
      <div class="drawer-content">
        <h3>Form 1 数据：</h3>
        <div class="drawer-json-container">
          <pre class="drawer-json-display">{{ formattedJson1 }}</pre>
        </div>
        
        <h3>Form 2 数据：</h3>
        <div class="drawer-json-container">
          <pre class="drawer-json-display">{{ formattedJson2 }}</pre>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw, computed } from 'vue'
import { message, Upload } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { filterOption } from '@/utils/selectOptions.ts'

const formRef1 = ref()
const formState1 = reactive({
  id: '',
  app: '',
  url: '',
  icon: [] as any,
})
const rules1 = {
  app: [
    {
      required: true,
      message: '请选择页面名称',
      trigger: 'change',
    },
  ],
}
const handleBeforeUpload = (file) => {
  console.log('beforeUpload', file)
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传jpg, png格式')
  }
  const isOverSize = file.size / 1024 / 1024 < 20
  if (!isOverSize) {
    message.error('图片尺寸超过' + 20 + '+MB!')
  }
  return (isJpgOrPng && isOverSize) || Upload.LIST_IGNORE
}
const submit1 = () => {
  formRef1.value
    .validate()
    .then(() => {
      console.log('values', formState1, toRaw(formState1))
      message.success('编辑成功')
    })
    .catch((error) => {
      console.log('error', error)
    })
}

const formRef2 = ref()
const formState2 = reactive({
  name: '',
  subordinate: undefined as any,
  principal: undefined as any,
  value2: '',
  value3: '',
  value4: undefined,
  value5: undefined,
})
// 自定义校验规则
const validateNumber = (_, value) => {
  /* if (!value) {
    return Promise.reject('请输入最小值')
  } */
  if (Number(value) < 0) {
    return Promise.reject('只能输入大于等于0的数字')
  }
  if (isNaN(Number(value))) {
    return Promise.reject('只能输入数字')
  }
  if (Number(value) > Number(formState2.value3)) {
    return Promise.reject('不能大于最大值')
  }
  return Promise.resolve()
}

const validateValue3 = (_, value) => {
  /* if (!value) {
    return Promise.reject('请输入最大值')
  } */
  if (isNaN(Number(value))) {
    return Promise.reject('只能输入数字')
  }
  if (Number(value) < Number(formState2.value2)) {
    return Promise.reject('不能小于最大值')
  }
  return Promise.resolve()
}
const rules2 = {
  name: [
    {
      required: true,
      message: '请输入组织名称',
      trigger: 'change',
    },
    {
      min: 1,
      max: 16,
      message: '超过最大16字符',
      trigger: 'change',
    },
  ],
  subordinate: [
    {
      required: true,
      message: '请选择上级组织',
      trigger: 'change',
    },
  ],
  value2: [
    {
      required: true,
      message: '请输入最小值',
      trigger: 'change',
    },
    { validator: validateNumber },
  ],
  value3: [
    {
      required: true,
      message: '请输入最大值',
      trigger: 'change',
    },
    { validator: validateValue3 },
  ],
}
const labelCol2 = {
  span: 7,
}
const wrapperCol2 = {
  span: 15,
}

const options = ref([{ label: '11', value: 1 }])
const options2 = ref([])
const options4 = ref([
  { label: '张三', value: 1 },
  { label: '李四', value: 2 },
])
const options5 = ref([
  { label: '会签', value: 1 },
  { label: '或签', value: 2 },
])

const submit2 = () => {
  formRef2.value
    .validate()
    .then(() => {
      console.log('values', formState2, toRaw(formState2))
      message.success('编辑成功')
    })
    .catch((error) => {
      console.log('error', error)
    })
}

// 侧边栏相关逻辑
const drawerVisible = ref(false)

const showDrawer = () => {
  drawerVisible.value = true
}

// 格式化表单数据为JSON展示
const formattedJson1 = computed(() => {
  const formattedString = JSON.stringify(toRaw(formState1), null, 2)

  // 移除第一行的缩进，保留其他行的缩进
  const lines = formattedString.split('\n')
  if (lines.length > 0) {
    // 移除第一行的空白
    lines[0] = lines[0].trimStart()
  }

  return lines.join('\n')
})

const formattedJson2 = computed(() => {
  const formattedString = JSON.stringify(toRaw(formState2), null, 2)

  // 移除第一行的缩进，保留其他行的缩进
  const lines = formattedString.split('\n')
  if (lines.length > 0) {
    // 移除第一行的空白
    lines[0] = lines[0].trimStart()
  }

  return lines.join('\n')
})
</script>
<style lang="scss">
.standardForm {
  h1 {
    height: 40px;
    line-height: 40px;
    font-size: 22px;
    font-weight: 700;
    border-bottom: 1px solid #ccc;
    margin: 10px 0;
    background: #ccc;
    padding-left: 10px;
  }
  section {
    border: 1px dashed #000;
    padding: 10px;
  }

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h1 {
      margin: 10px 0;
      flex: 1;
    }
  }

  .result-container {
    h3 {
      margin-top: 16px;
      margin-bottom: 8px;
    }
  }

  .json-container {
    margin: 10px 0;
  }

  .json-display {
    margin: 0;
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    max-width: 100%;
    overflow-x: auto;
    white-space: pre;
    font-family: 'Courier New', Courier, monospace;
    line-height: 1.5;
    text-indent: 0;
  }
}

// 独立的侧边栏样式，不受.standardForm层级限制
.form-result-drawer {
  .drawer-content {
    h3 {
      margin-top: 16px;
      margin-bottom: 8px;
      font-size: 16px;
      font-weight: bold;
    }
  }
  
  .drawer-json-container {
    margin: 10px 0;
  }

  .drawer-json-display {
    margin: 0;
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    max-width: 100%;
    overflow-x: auto;
    white-space: pre;
    font-family: 'Courier New', Courier, monospace;
    line-height: 1.5;
    text-indent: 0;
  }
}
</style>
